package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustomException;
import com.heima.file.service.FileStorageService;
import com.heima.model.Utils.threadlocal.WmThreadLocalUtils;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dto.WmMaterialDto;
import com.heima.model.wemedia.pojo.WmMaterial;
import com.heima.model.wemedia.pojo.WmNewsMaterial;
import com.heima.model.wemedia.pojo.WmUser;
import com.heima.wemedia.mapper.MaterialMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.MaterialService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * Created by ZYJ on 2021/5/26 20:47
 */
@Slf4j
@Service
public class MaterialServiceImpl extends ServiceImpl<MaterialMapper, WmMaterial> implements MaterialService {
    @Autowired
    private FileStorageService fileStorageService;
    @Autowired
    private WmNewsMaterialMapper newsMaterialMapper;
    @Value("${file.oss.profix}")
    String profix;
    @Value("${file.oss.web-site}")
    String webSite;

    /**
     * 自媒体人 素材上传
     *
     * @param multipartFile
     * @return
     */
    @Override
    public ResponseResult uploadPicture(MultipartFile multipartFile) {
        if (multipartFile == null || multipartFile.getSize() == 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE, "文件不可为空");
        }
        if (WmThreadLocalUtils.getUser().getId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "用户未登录");
        }
        //2.上传文件到oss  生成文件的名称 截取原始文件的后缀
        //随机生成UUID文件名 去掉-
        String filename = UUID.randomUUID().toString().replace("-", "");
        //获取原始文件名的后缀
        int index = multipartFile.getOriginalFilename().lastIndexOf('.');
        String sufix = multipartFile.getOriginalFilename().substring(index);
        //上传到oss
        try {
            String url = fileStorageService.store(profix, filename + sufix, multipartFile.getInputStream());
            //3.创建素材表信息,将图片路径存入
            WmMaterial material = new WmMaterial();
            material.setId(null);
            material.setUserId(WmThreadLocalUtils.getUser().getId());
            material.setUrl(url); //oss返回的路径
            material.setType((short) 0);
            material.setIsCollection((short) 0);
            material.setCreatedTime(new Date());
            //将素材保存到数据库
            this.save(material);
            //给前端的url是可以访问的路径
            material.setUrl(webSite + url);
            return ResponseResult.okResult(material);


        } catch (IOException e) {
            log.error("文件上传出错==>{}", e.getMessage());
            throw new CustomException(AppHttpCodeEnum.SERVER_ERROR, "文件上传失败");
        }
    }

    /**
     * 素材列表加载
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findList(WmMaterialDto dto) {
        //检验参数
        dto.checkParam();
        LambdaQueryWrapper<WmMaterial> wrapper = new LambdaQueryWrapper<>();
        //是收藏加条件
        if (dto.getIsCollection() != null && dto.getIsCollection() == 1) {
            wrapper.eq(WmMaterial::getIsCollection, dto.getIsCollection());
        }

        Integer userId = WmThreadLocalUtils.getUser().getId();
        if (userId == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        wrapper.eq(WmMaterial::getUserId, userId);
        wrapper.orderByDesc(WmMaterial::getCreatedTime);

        IPage<WmMaterial> page = new Page<>(dto.getPage(), dto.getSize());

        IPage<WmMaterial> pageResult = page(page, wrapper);
        //图片要加上前缀使其可外部访问
        List<WmMaterial> materialList = pageResult.getRecords();
        if (materialList != null && materialList.size() > 0) {
            for (WmMaterial wmMaterial : materialList) {
                wmMaterial.setUrl(webSite + wmMaterial.getUrl());
            }
        }
        PageResponseResult pageResponseResult = new PageResponseResult();
        pageResponseResult.setSize(dto.getSize());
        pageResponseResult.setCurrentPage(dto.getPage());
        pageResponseResult.setTotal(pageResult.getTotal());
        pageResponseResult.setData(materialList);
        return pageResponseResult;

    }

    /**
     * 删除素材
     *
     * @param id
     * @return
     */
    @Override
    @Transactional //操作两张表
    public ResponseResult deleteMaterial(Integer id) {
        if (id == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        WmMaterial material = getById(id);
        if (material == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        if (WmThreadLocalUtils.getUser() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //查找引用表 如果被引用则不能删除
        Integer count = newsMaterialMapper.selectCount(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getMaterialId, id));
        if (count != 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR, "数据被引用,需先删除引用文章");
        }
        //oss
        fileStorageService.delete(material.getUrl());
        //删除素材表
        removeById(id);

        return ResponseResult.okResult();
    }

    /**
     * 收藏与取消收藏素材
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult collectionMaterial(Integer id, Short type) {
        if (id == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmUser user = WmThreadLocalUtils.getUser();
        if(user ==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        update(Wrappers.<WmMaterial>lambdaUpdate()
                .set(WmMaterial::getIsCollection, type)
                .eq(WmMaterial::getId, id)
                .eq(WmMaterial::getUserId, user.getId()));
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);

    }

}
